package com.ecoolex.discount.sales.core.service;

import com.ecoolex.admin.system.core.manager.AdminCurrencyTypeExchangeRateManager;
import com.ecoolex.admin.system.entity.AdminCurrencyTypeExchangeRate;
import com.ecoolex.discount.sales.core.external.YouWorldExternalService;
import com.ecoolex.discount.sales.core.external.pojo.YouWorldCardStatusResult.YouWorldCardStatus;
import com.ecoolex.discount.sales.core.external.pojo.YouWorldCheckRefundStatusResult.YouWorldCheckRefundStatus;
import com.ecoolex.discount.sales.core.external.pojo.YouWorldExchangeRateResult.YouWorldExchangeRate;
import com.ecoolex.discount.sales.core.external.pojo.YouWorldGenerateGiftCardRequest;
import com.ecoolex.discount.sales.core.external.pojo.YouWorldLoginResult.YouWorldToken;
import com.ecoolex.discount.sales.core.external.pojo.YouWorldOrder;
import com.ecoolex.discount.sales.core.external.pojo.YouWorldSendRefundRequest;
import com.ecoolex.discount.sales.core.manager.*;
import com.ecoolex.discount.sales.entity.*;
import com.ecoolex.discount.sales.enums.*;
import com.ecoolex.discount.sales.pojo.AddDiscountProductDTO;
import com.ecoolex.discount.sales.pojo.EditDiscountProductGiftCardDTO;
import com.ecoolex.discount.sales.pojo.YouWorldServiceProviderInfoDTO;
import com.ecoolex.framework.common.util.*;
import com.ecoolex.framework.common.util.crypto.MD5Util;
import com.ecoolex.framework.common.util.io.IOUtil;
import com.ecoolex.framework.modularize.api.service.cache.CacheService;
import com.ecoolex.framework.modularize.api.service.storage.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;

import static com.ecoolex.discount.sales.core.external.pojo.YouWorldAccountBalanceResult.*;
import static com.ecoolex.discount.sales.core.external.pojo.YouWorldCatalogsResult.*;

@Service
public class YouWorldService {

    private static final Logger log = LoggerFactory.getLogger(YouWorldService.class);

    @Value("${you.world.username}")
    private String username;
    @Value("${you.world.password}")
    private String password;
    @Value("${you.world.email}")
    private String email;
    @Value("${weixin.pay.mch-id}")
    private String weixinMchId;
    @Value("${nihao.pay.mch-id}")
    private String nihaoPayMchId;

    @Autowired
    private CacheService cacheService;
    @Autowired
    private StorageService storageService;
    @Autowired
    private YouWorldExternalService youWorldExternalService;
    @Autowired
    private DiscountBrandManager discountBrandManager;
    @Autowired
    private DiscountProductManager discountProductManager;
    @Autowired
    private DiscountProductGiftCardManager discountProductGiftCardManager;
    @Autowired
    private YouWorldGiftCardManager youWorldGiftCardManager;
    @Autowired
    private YouWorldGiftCardOrderManager youWorldGiftCardOrderManager;
    @Autowired
    private DiscountOrderDetailManager discountOrderDetailManager;
    @Autowired
    private DiscountOrderOutinfoManager outinfoManager;
    @Autowired
    private AdminCurrencyTypeExchangeRateManager adminCurrencyTypeExchangeRateManager;
    @Autowired
    private MarketingClassifyBrandManager marketingClassifyBrandManager;
    @Autowired
    private DiscountOrderRefundManager discountOrderRefundManager;
    @Autowired
    private DiscountOrderManager discountOrderManager;
    @Autowired
    private CardVoucherPackageManager cardVoucherPackageManager;

    private static final UploadSource IMAGE_SOURCE = UploadSource.builder().withSource("YouWorldGiftCard").withSourceValue("Image").build();
    private static final UploadLimit IMAGE_LIMIT = UploadLimit.builder().withMaxSize(FileSize.MB.byteLength(10)).withAllowMimeType(MimeType.IMAGE.alls()).build();


    public YouWorldServiceProviderInfoDTO getServiceProviderInfo() {
        YouWorldAccountBalance accountBalance = youWorldExternalService.accountBalance(getToken());
        YouWorldServiceProviderInfoDTO result = new YouWorldServiceProviderInfoDTO();
        result.setBalance(accountBalance.getBalance());
        result.setCurrency(accountBalance.getCurrency());
        result.setCurrency_unit(accountBalance.getCurrency_unit());
        return result;
    }
    /**
     * 预设1分钟一次
     */
    public synchronized void refreshToken() {
        long effectiveTime = cacheService.getEffectiveTime(buildCacheKey());
        // 如果有效期小于1小时则更新
        if (effectiveTime < Duration.of(1, ChronoUnit.DAYS).toMillis()) {
            generateToken();
        }
    }

    /**
     * 预设1分钟一次
     */
    public synchronized void refreshAccountStatus() {
        if (checkAccountState()) {
            // 合法的同步所有产品可用状态
            syncProduct();
        } else {
            // 不合法, 标记所有产品为不可用
            disableAllProduct();
        }
    }

    /**
     * 预设10分钟一次
     */
    public synchronized void refreshCards() {
        syncApiData();
    }

    public void validityVerify(DiscountProduct product) {
        BizAssert.isTrue(Check.notNullOrTrimEmpty(product.getServiceDataId()), "服务数据为空");
        BizAssert.isTrue(Check.isNumber(product.getServiceDataId()), "服务数据不是数字");
        BizAssert.isTrue(Check.notNull(youWorldGiftCardManager.getByCardId(Integer.valueOf(product.getServiceDataId()))), "由我礼品卡不存在");
    }

    public void onlineVerify(DiscountProduct product, DiscountProductGiftCard record) {
        validityVerify(product);
        YouWorldGiftCard giftCard = youWorldGiftCardManager.getByCardId(Integer.valueOf(product.getServiceDataId()));
        BizAssert.isTrue(Check.notNull(giftCard), "由我礼品卡不存在");
        DiscountProductGiftCardCounterPriceType counterPriceType = DiscountProductGiftCardCounterPriceType.realValueOf(record.getCounterPriceType());
        BizAssert.isTrue(Check.notNull(counterPriceType), "价格类型不能为空");
        BizAssert.isTrue(Check.notNullOrTrimEmpty(record.getCurrencyType()) && "USD".equalsIgnoreCase(record.getCurrencyType()), "由我礼品卡币种不能为空并且只支持USD");

        if (counterPriceType == DiscountProductGiftCardCounterPriceType.FIXED) {
            BizAssert.isTrue(Check.notNull(record.getMaxBuyNumber()), "由我礼品卡购买数量不能为空");
        }

        DiscountProductGiftCardCounterPriceType youWorldCounterPriceType = DiscountProductGiftCardCounterPriceType.getCounterPriceType(giftCard);
        if (youWorldCounterPriceType == DiscountProductGiftCardCounterPriceType.FIXED) {
            // 固定价格, 如果固定价格,
            BizAssert.isTrue(DiscountProductGiftCardCounterPriceType.FIXED.equal(record.getCounterPriceType()), "由我礼品卡为固定价格类型,只支持固定价格类型");
            BizAssert.isTrue(Check.notNull(record.getCounterPrice()), "专柜价不能为空");
            BizAssert.isTrue(Check.notNullAndGtZero(record.getRetailPrice()), "零售价不能为空并且大于零");
            //BizAssert.isTrue(record.getRetailPrice().scale() <= 2, "零售价只支持最大2位小数设置");
            BigDecimal giftCardPrice = BigDecimal.valueOf(giftCard.getFaceValue()).divide(HUNDRED);
            BizAssert.isTrue(record.getCounterPrice().compareTo(giftCardPrice)==0, "专柜价必须与由我礼品卡面额[{}]一致", giftCardPrice);
        } else {
            BigDecimal minPrice = BigDecimal.valueOf(giftCard.getCardMinValue()).divide(HUNDRED);
            BigDecimal maxPrice = BigDecimal.valueOf(giftCard.getCardMaxValue()).divide(HUNDRED);

            if (counterPriceType == DiscountProductGiftCardCounterPriceType.FIXED) {
                BizAssert.isTrue(Check.isRangeWithin(record.getCounterPrice(), minPrice, maxPrice), "专柜价不能超出由我礼品卡面额[{}-{}]区间", minPrice, maxPrice);
                BizAssert.isTrue(Check.notNullAndGtZero(record.getRetailPrice()), "零售价不能为空并且大于零");
                //BizAssert.isTrue(record.getRetailPrice().scale() <= 2, "零售价只支持最大2位小数设置");
            } else {
                // 动态价格也必须在范围内
                BizAssert.isTrue(Check.isGreatThanEqual(record.getMinCounterPrice(), minPrice), "最小专柜价必须大于等于{}", minPrice);
                BizAssert.isTrue(Check.isLessThanEqual(record.getMaxCounterPrice(), maxPrice), "最大专柜价必须小于于等于{}", maxPrice);
                BizAssert.isTrue(Check.isLessThan(record.getMinCounterPrice(), record.getMaxCounterPrice()), "最小专柜价必须小于最大专柜价");
                BizAssert.isTrue(Check.notNullAndGteZero(record.getCounterPriceDiscountPercent()) && Check.isLessThan(record.getCounterPriceDiscountPercent(), HUNDRED) , "折扣率不能为空并且必须大于等于0小于100");
            }
        }
    }

    private String buildCacheKey() {
        return MessageFormatter.arrayFormat("/discount/sales/you/world/{}/{}/token", username, MD5Util.encrypt(password));
    }

    private boolean checkAccountState() {
        YouWorldAccountBalance accountBalance = youWorldExternalService.accountBalance(getToken());
        // 如果账户余额小于100美分则为失效
        // 检查账户状态
        // 如果是余额不足, 直接不合法
        // 如果是调用异常则在10分钟内三次异常则标记为异常???
        return accountBalance.getBalance() >= 100;
    }

    private void disableAllProduct() {
        List<DiscountProductWithBLOBs> productList = discountProductManager.queryByServiceType(DiscountProductServiceType.YOU_WORLD);
        productList.forEach(product -> {
            // 检查状态是否与数据库数据相等, 不相等则更新
            if (DiscountProductAvailableStatus.DISABLE.notEqual(product.getAvailableStatus())) {
                discountProductManager.setDisableAvailable(product.getProductId(), this.getClass().getSimpleName());
            }
        });
    }

    private static final BigDecimal HUNDRED = new BigDecimal("100");

    private void addProduct(YouWorldGiftCard youWorldGiftCard) {
        // 根据名称查找品牌
        DiscountBrand brand = discountBrandManager.getByName(youWorldGiftCard.getCardName());
        if (Check.isNull(brand)) {
            // 如果未找到品牌,则不处理
            return;
        }
        // 生成产品可用状态
        DiscountProductAvailableStatus availableStatus = getDiscountProductAvailableStatus(youWorldGiftCard);
        DiscountProductGiftCardCounterPriceType counterPriceType = DiscountProductGiftCardCounterPriceType.getCounterPriceType(youWorldGiftCard);

        // 添加产品
        AddDiscountProductDTO product = new AddDiscountProductDTO();
        product.setBrandId(brand.getBrandId());
        product.setRegionType(DiscountProductRegionType.OVERSEAS.real());
        product.setDiscountMode(DiscountProductDiscountMode.GIFT_CARD.real());
        product.setServiceType(DiscountProductServiceType.YOU_WORLD.real());
        product.setServiceDataId(String.valueOf(youWorldGiftCard.getCardId()));
        product.setName(youWorldGiftCard.getCardName());
        product.setSubTitle(null);
        product.setShelfLifeStrategy(DiscountProductShelfLifeStrategy.UNKNOWN.real());
        try {
            // 下载图片
            try (InputStream is = new URL(youWorldGiftCard.getCardImage()).openConnection().getInputStream()) {
                byte[] data = IOUtil.readByte(is);

                UploadBytes request = new UploadBytes();
                request.setFileName("you_world_image.jpg");
                request.setData(data);

                // 下载图片
                StorageInfo storageInfo = storageService.upload(request, IMAGE_SOURCE, IMAGE_LIMIT);
                product.setImage(storageInfo.getStorageId());
            }
        } catch (Exception exception) {
            log.error("由我礼品卡下载图片异常", exception);
        }
        DiscountProductWithBLOBs discountProduct = discountProductManager.create(product, this.getClass().getSimpleName());

        EditDiscountProductGiftCardDTO edit = new EditDiscountProductGiftCardDTO();

        if (counterPriceType == DiscountProductGiftCardCounterPriceType.FIXED) {
            // 固定价格
            edit.setCounterPriceType(DiscountProductGiftCardCounterPriceType.FIXED.real());
            edit.setCounterPrice(BigDecimal.valueOf(youWorldGiftCard.getFaceValue()).divide(HUNDRED));
            edit.setRetailPrice(edit.getCounterPrice().multiply(HUNDRED.subtract(youWorldGiftCard.getCardDiscountPercent()).divide(HUNDRED)));
            edit.setCounterPriceDiscountPercent(youWorldGiftCard.getCardDiscountPercent());
        } else {
            // 价格区间和折扣率
            edit.setCounterPriceType(DiscountProductGiftCardCounterPriceType.VARIABLE.real());
            edit.setMinCounterPrice(BigDecimal.valueOf(youWorldGiftCard.getCardMinValue()).divide(HUNDRED));
            edit.setMaxCounterPrice(BigDecimal.valueOf(youWorldGiftCard.getCardMaxValue()).divide(HUNDRED));
            edit.setCounterPriceDiscountPercent(youWorldGiftCard.getCardDiscountPercent());
        }
        edit.setCurrencyType("USD");

        // 编辑礼品卡信息
        discountProductGiftCardManager.update(discountProduct.getProductId(), edit, this.getClass().getSimpleName());
        // 添加完修改成正常状态
        youWorldGiftCardManager.setAdded(youWorldGiftCard, this.getClass().getSimpleName());
    }

    private DiscountProductAvailableStatus getDiscountProductAvailableStatus(YouWorldGiftCard youWorldGiftCard) {
        YouWorldGiftCardStatus status = YouWorldGiftCardStatus.realValueOf(youWorldGiftCard.getStatus());
        // 产品的启用状态; 默认禁用
        if (YouWorldGiftCardStatus.NORMAL == status) {
            if (youWorldGiftCard.getStorefrontStatus().equalsIgnoreCase("active")) {
                return DiscountProductAvailableStatus.ENABLE;
            }
        }
        return DiscountProductAvailableStatus.DISABLE;
    }

    private void syncProduct() {
        // 查询账户状态和账户是否有余额,或者最少余额, 如果不合理则需要下线所有礼品卡产品
        if (!checkAccountState()) {
            log.info("账户状态不合法, 停止更新产品状态");
        }

        List<YouWorldGiftCard> giftCardList = youWorldGiftCardManager.queryAll();
        giftCardList.forEach(youWorldGiftCard -> {
        	YouWorldGiftCardStatus status = YouWorldGiftCardStatus.realValueOf(youWorldGiftCard.getStatus());
        	BigDecimal ywPercent = youWorldGiftCard.getCardDiscountPercent();
        	Integer ranking = youWorldGiftCard.getRanking();
            // 新增的添加到数据库，暂时只支持手动发到产品库
//            if (youWorldGiftCard.getIsAdded()) {
//                addProduct(youWorldGiftCard);
//                return;
//            }
            // 生成产品可用状态
            DiscountProductAvailableStatus availableStatus = getDiscountProductAvailableStatus(youWorldGiftCard);
            // 迭代所有产品
            List<DiscountProductWithBLOBs> productList = discountProductManager.queryByServiceTypeAndServiceDataId(DiscountProductServiceType.YOU_WORLD, String.valueOf(youWorldGiftCard.getCardId()));
            productList.forEach(product -> {
                // 根据供应商库存更新产品可用状态，检查状态是否与数据库数据相等, 不相等则更新
                if (availableStatus.notEqual(product.getAvailableStatus())) {
                	//从供应商获取到的是有库存状态
                	if(DiscountProductAvailableStatus.ENABLE.equal(availableStatus.real())) {
                		discountProductManager.setEnableAvailable(product.getProductId(), this.getClass().getSimpleName());
                	}else {
                		//供应商产品无库存
                		discountProductManager.setDisableAvailable(product.getProductId(), this.getClass().getSimpleName());
                	}
                }
                //更新产品-礼品卡折扣率
                DiscountProductGiftCard giftCard = discountProductGiftCardManager.getByProductId(product.getProductId());
                if(Check.notNull(giftCard) && Check.notEqNullable(ywPercent, giftCard.getCounterPriceDiscountPercent())) {
                	giftCard.setCounterPriceDiscountPercent(ywPercent);
                	discountProductGiftCardManager.updatePercent(giftCard, this.getClass().getSimpleName());
                }
                //更新产品上下架状态
                if(YouWorldGiftCardStatus.NOT_FOUND_SYNC_DATA.equal(status.real()) && DiscountProductStatus.canOffline(product)) {
                	discountProductManager.offline(product.getProductId(), this.getClass().getSimpleName());
                }else if(YouWorldGiftCardStatus.NORMAL.equal(status.real()) && DiscountProductStatus.canOnline(product)) {
                	discountProductManager.online(product.getProductId(), this.getClass().getSimpleName());
                }
                //更新分类营销下的品牌排序字段
                List<MarketingClassifyBrand> marketingClassifyBrandList = marketingClassifyBrandManager.queryByBrandId(product.getBrandId());
                marketingClassifyBrandList.forEach(marketingClassifyBrand -> {
                	if(Check.notEqNullable(ranking, marketingClassifyBrand.getWeight())){
                		marketingClassifyBrand.setWeight(ranking);
                		marketingClassifyBrandManager.editMarketingClassifyBrand(marketingClassifyBrand, this.getClass().getSimpleName());
                	}
                });
            });
        });
    }

    private void syncApiData() {
        List<YouWorldGiftCard> giftCardList = youWorldGiftCardManager.queryAll();

        // 同步接口数据到表
        List<Card> cardList = youWorldExternalService.catalogs(getToken());
        cardList.forEach(card -> {
            if (Check.notNull(card.getCard_id())) {
                YouWorldGiftCard oldCard = giftCardList.stream().collect(CollectorUtil.first(giftCard -> giftCard.getCardId().equals(card.getCard_id())));
                // 判断数据是否上传到数据库
                if (Check.isNull(oldCard)) {
                    youWorldGiftCardManager.create(card, this.getClass().getSimpleName());
                } else {
                    youWorldGiftCardManager.update(oldCard, card, this.getClass().getSimpleName());
                    giftCardList.remove(oldCard);
                }
            }
            if (Check.notNullOrEmpty(card.getFixed_cards())) {
                card.getFixed_cards().forEach(fixedCard -> {
                    YouWorldGiftCard oldCard = giftCardList.stream().collect(CollectorUtil.first(giftCard -> giftCard.getCardId().equals(fixedCard.getCard_id())));
                    if (Check.isNull(oldCard)) {
                        youWorldGiftCardManager.create(card, fixedCard, this.getClass().getSimpleName());
                    } else {
                        youWorldGiftCardManager.update(oldCard, card, fixedCard, this.getClass().getSimpleName());
                        giftCardList.remove(oldCard);
                    }
                });
            }
        });

        // 剩下的标记异常
        giftCardList.forEach(card -> youWorldGiftCardManager.setNotFoundSyncData(card, this.getClass().getSimpleName()));
    }

    private YouWorldToken getToken() {
        byte[] bytes = cacheService.getBytes(buildCacheKey());
        if (Check.isNullOrEmpty(bytes)) {
            return generateToken();
        }
        YouWorldToken token = Objects.deserialization(bytes);
        return token;
    }

    private YouWorldToken generateToken() {
        YouWorldToken token = youWorldExternalService.login(username, password);
        cacheService.putBytes(buildCacheKey(), Objects.serialization(token), Duration.between(Instant.now(), token.getExpires_at().toInstant()).toMillis());
        return token;
    }
    
    /**
     * 检查礼品卡可用状态
     * @param cardId
     * @return
     */
    public Boolean checkCardStatus(Integer cardId) {
    	YouWorldCardStatus cardStatus = youWorldExternalService.cardStatus(getToken(), cardId);
    	
    	return cardStatus.getStorefront_status().equalsIgnoreCase("active") ? true : false;
    }
    
    /**
     * 获取最新USD转CNY汇率
     */
    public void refreshExchangeRate() {
    	YouWorldExchangeRate exchangeRate = youWorldExternalService.exchangeRate(getToken());
    	AdminCurrencyTypeExchangeRate old = adminCurrencyTypeExchangeRateManager.getById("USD", "CNY");
    	if(Check.isNull(old)) {
    		AdminCurrencyTypeExchangeRate record = new AdminCurrencyTypeExchangeRate();
    		record.setCurrencyKey("USD");
    		record.setExchangeCurrencyKey("CNY");
    		record.setExchangeRate(exchangeRate.getExchange_rate());
    		adminCurrencyTypeExchangeRateManager.add(record, YouWorldService.class.getSimpleName());
    	}else {
    		old.setExchangeRate(exchangeRate.getExchange_rate());
    		adminCurrencyTypeExchangeRateManager.update(old, YouWorldService.class.getSimpleName());
    	}
    }
    
    /**
     * 向由我付发起退款申请
     * @param orderId
     * @param cardUsed
     * @param reasonType
     * @param reasonComments
     * @param phone
     * @return
     */
    public Boolean sendRefundRequest(String orderId,Boolean cardUsed,String reasonType,String reasonComments,String phone) {
    	YouWorldSendRefundRequest request = new YouWorldSendRefundRequest();
    	request.setOrderId(orderId);
    	request.setCardUsed(cardUsed);
    	request.setReasonType(reasonType);
    	request.setReasonComments(reasonComments);
    	request.setPhone(phone);
    	return youWorldExternalService.sendRefundRequest(getToken(), request);
    }
    
    /**
     * 向由我付取消退款申请
     * @param orderId
     * @return
     */
    public Boolean cancelRefundRequest(String orderId) {
    	return youWorldExternalService.cancelRefundRequest(getToken(), orderId);
    }
    
    public void refreshRefundStatusList(List<DiscountOrder> orderList) {
    	orderList.forEach(order -> {
    		refreshRefundStatus(order);
    	});
    }
    
    public void refreshRefundStatus(DiscountOrder order) {
    	if(DiscountProductServiceType.YOU_WORLD.equal(order.getServiceType()) 
			&& DiscountOrderStatus.REFUND.equal(order.getOrderStatus())) {
			List<DiscountOrderDetail> orderDetailList = discountOrderDetailManager.queryByOrderId(order.getOrderId());
			if(Check.notNullOrEmpty(orderDetailList)) {
				YouWorldCheckRefundStatus youWorldCheckRefundStatus = checkRefundStatus(orderDetailList.get(0).getTransNo());
				DiscountOrderRefund orderRefund = discountOrderRefundManager.getByOrderId(order.getOrderId());
				orderRefund.setAmount(BigDecimal.valueOf(youWorldCheckRefundStatus.getOrder_amount()).divide(HUNDRED));
				orderRefund.setCardUsed(youWorldCheckRefundStatus.getCard_used());
				orderRefund.setCustomerServiceReply(youWorldCheckRefundStatus.getCustomer_service_reply());
				orderRefund.setRefundStatus(youWorldCheckRefundStatus.getRefund_status());
				orderRefund.setUpdateTime(Date.from(Instant.now()));
				discountOrderRefundManager.update(orderRefund, this.getClass().getSimpleName());
				if("processing".equalsIgnoreCase(youWorldCheckRefundStatus.getRefund_status())) {
					order.setRefundStatus(DiscountOrderRefundStatus.REFUNDING.real());
				}else if("refund_success".equalsIgnoreCase(youWorldCheckRefundStatus.getRefund_status())) {
					order.setRefundStatus(DiscountOrderRefundStatus.REFUND_SUCCEED.real());
					cardVoucherPackageManager.delete(order.getOrderId(), this.getClass().getSimpleName());
				}else if("refused".equalsIgnoreCase(youWorldCheckRefundStatus.getRefund_status())) {
					order.setRefundStatus(DiscountOrderRefundStatus.REFUND_FAILED.real());
				}
				discountOrderManager.update(order, this.getClass().getSimpleName());
			}
		}
    }
    
    /**
     * 查询退款状态
     * @param orderId
     * @return
     */
    private YouWorldCheckRefundStatus checkRefundStatus(String orderId) {
    	
    	return youWorldExternalService.checkRefundStatus(getToken(), orderId);
    }

    public void processOrder(DiscountOrder order, DiscountProductGiftCard giftCard, String updateUser) {
    	DiscountOrderOutinfo discountOrderOutinfo = outinfoManager.getByOrderId(order.getOrderId());
        // 生成礼品卡
        YouWorldGenerateGiftCardRequest request = new YouWorldGenerateGiftCardRequest();
        request.setFaceValue(order.getBuyTotalCounterPrice().multiply(new BigDecimal("100")).intValue());
        request.setAgentCardId(Integer.valueOf(order.getServiceDataId()));
        request.setEmail(email);
        if(Check.notNull(discountOrderOutinfo)) {
        	request.setPlatform(DiscountOrderChannel.realValueOf(discountOrderOutinfo.getChannel()).describe());
        }else {
        	request.setPlatform("wechat");
        }
        request.setPayerId(String.valueOf(order.getUserId()));
        request.setMobileNumber(order.getMobileNumber());
        request.setPaymentGateway(DiscountOrderPaymentChannel.realValueOf(order.getPaymentChannel()).describe());
        if(DiscountOrderPaymentChannel.NIHAO_PAY.equal(order.getPaymentChannel())) {
        	request.setMerchantId(nihaoPayMchId);
        }else if(DiscountOrderPaymentChannel.WEI_XIN.equal(order.getPaymentChannel())){
        	request.setMerchantId(weixinMchId);
        }
        request.setReference(order.getOrderNo());
        request.setTransactionId(order.getPaymentNo());
        YouWorldOrder result = youWorldExternalService.generateGiftCard(getToken(), request);
        // 创建调用记录
        youWorldGiftCardOrderManager.save(result, updateUser);
        // 判断卡的订单状态
        DiscountOrderDetail detail = new DiscountOrderDetail();
        detail.setTransNo(result.getOrder_id());
        detail.setVoucherNumber(result.getCard_barcode_number());
        detail.setVoucherPass(result.getCard_pin_number());
        detail.setIsMainProduct(true);
        detail.setProductId(giftCard.getProductId());
        // 添加订单详情
        discountOrderDetailManager.add(order, detail, updateUser);
    }
}